package com.kalix.mooc.school.biz;

import com.kalix.framework.core.impl.biz.ShiroGenericBizServiceImpl;
import com.kalix.mooc.school.api.biz.ISchoolListBeanService;
import com.kalix.mooc.school.api.dao.ISchoolListBeanDao;
import com.kalix.mooc.school.api.dto.SchoolTreeDTO;
import com.kalix.mooc.school.entities.SchoolListBean;

import java.util.ArrayList;
import java.util.List;

public class SchoolListBeanServiceImpl extends ShiroGenericBizServiceImpl<ISchoolListBeanDao, SchoolListBean> implements ISchoolListBeanService {
    @Override
    public SchoolTreeDTO getAllSchoolList(Long id) {
        SchoolTreeDTO school = new SchoolTreeDTO();
        List<SchoolTreeDTO> schoolTreeDTO = new ArrayList<>();
        //所有数据
        String  sql = "select * from mooc_schoolList";
        List<SchoolListBean> beans = dao.findByNativeSql(sql, SchoolListBean.class);
        if (beans != null && beans.size() > 0) {
            //一级目录
            List<SchoolListBean> rootElements = getRootElements(beans);
            if (rootElements != null && rootElements.size() > 0) {
                for (SchoolListBean rootElement : rootElements) {
                    SchoolTreeDTO a = new SchoolTreeDTO();
                    a.setId(rootElement.getId());
                    a.setParentId(rootElement.getParentId());
                    a.setName(rootElement.getName());
                    a.setCode(rootElement.getCode());
                    a.setChildren(getChildren(rootElement,beans));
                    schoolTreeDTO.add(a);
                }
            }
        }
        school.setChildren(schoolTreeDTO);
        return school;
    }

    private List<SchoolTreeDTO> getChildren(SchoolListBean one, List<SchoolListBean> beans) {
        List<SchoolTreeDTO> children = new ArrayList<>();
        for (SchoolListBean departmentsBean : beans) {
            SchoolTreeDTO a = new SchoolTreeDTO();
            if(one.getId()== departmentsBean.getParentId()) {
                a.setId(departmentsBean.getId());
                a.setParentId(departmentsBean.getParentId());
                a.setName(departmentsBean.getName());
                a.setCode(departmentsBean.getCode());
                a.setChildren(getChildren(departmentsBean,beans));
                children.add(a);
            }
        }
        return children;
    }

    //所有根目录
    private List<SchoolListBean> getRootElements(List<SchoolListBean> elements) {
        List<SchoolListBean> roots = new ArrayList<SchoolListBean>();
        for (SchoolListBean element : elements) {
            if (element.getParentId()== -1) {
                roots.add(element);
            }
        }
        return roots;
    }
}
